package com.kevin.eshopcache.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kevin.eshopcache.constants.Keys;
import com.kevin.eshopcache.entity.ProductInfo;
import com.kevin.eshopcache.entity.ShopInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisCluster;

/**
 * @author: e20160504
 * @date: 2018/11/2
 * @desc
 */
@Service("cacheService")
public class CacheServiceImpl implements CacheService {

    public static final String CACHE_NAME="local";
    @Autowired
    private JedisCluster jedisCluster;

    private static  String productKey = Keys.PRODUCT_CACHE_KEY;
    private static String shopKey = Keys.SHOP_CACHE_KEY;


    @Override
    @CachePut(value = CACHE_NAME, key = "'productInfo:key_' + #productInfo.getId()")
    public ProductInfo saveLocalCache(ProductInfo productInfo) {
            return productInfo;
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'productInfo:key_' + #id")
    public ProductInfo getLocalCache(Long id) {
        return null;
    }

    @Override
    @CachePut(value = CACHE_NAME, key = "'shopInfo:key_' + #shopInfo.getId()")
    public ShopInfo saveLocalShopCache(ShopInfo shopInfo) {
        return shopInfo;
    }

    @Override
    @Cacheable(value = CACHE_NAME, key = "'shopInfo:key_' + #id")
    public ShopInfo getLocalShopCache(Long id) {
        return null;
    }

    @Override
    public void saveRedisProductCache(ProductInfo productInfo){
        jedisCluster.set(productKey + productInfo.getId(), JSON.toJSONString(productInfo));
    }

    @Override
    public ProductInfo getRedisProductCache(Long productId){
        String s = jedisCluster.get(productKey + productId);
        if(!StringUtils.isEmpty(s)){
            return JSONObject.parseObject(s,ProductInfo.class);
        }
        return null;
    }

    @Override
    public void saveRedisShopCache(ShopInfo shopInfo){
        jedisCluster.set(shopKey + shopInfo.getId(), JSON.toJSONString(shopInfo));
    }

    @Override
    public ShopInfo getRedisShopCache(Long shopId){
        String s = jedisCluster.get(shopKey + shopId);
        if(!StringUtils.isEmpty(s)){
            return JSONObject.parseObject(s,ShopInfo.class);
        }
        return null;
    }
}
